from datetime import datetime, timedelta

from django.contrib.auth import get_user_model
from rest_framework import serializers

from rest_framework.validators import UniqueValidator

from app.users.models import VerifyCode

User = get_user_model()


class VerifyCodeSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(label='邮箱', allow_blank=False, allow_null=False)

    class Meta:
        model = VerifyCode
        fields = ['email']


class RegisterSerializer(serializers.ModelSerializer):
    # 原先的数据库中未定义code，需要手动添加
    code = serializers.CharField(write_only=True, label='验证码')
    username = serializers.CharField(label='用户名', validators=[UniqueValidator(User.objects.all(), message='用户名已注册')])
    phone = serializers.CharField(label='电话', validators=[UniqueValidator(User.objects.all(), message='电话已注册')])
    # 密码隐式输入
    password = serializers.CharField(style={'input_type': 'password'},
                                     label='密码',
                                     write_only=True)

    # 设置密码加密存储
    def create(self, validated_data):
        user = super(RegisterSerializer, self).create(validated_data=validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

    email = serializers.EmailField(label='邮箱', allow_null=False,
                                   validators=[UniqueValidator(User.objects.all(), message='邮箱已注册')])

    def validate_code(self, code):
        # 先查询该用户是否已经用邮箱接受过验证码
        # print(code)
        # print(self.initial_data['email'])
        verifycode = VerifyCode.objects.filter(email=self.initial_data['email']).order_by('-add_time').first()

        if verifycode:

            # 如果存在，验证验证码是否有效
            one_minute_ago = datetime.utcnow() - timedelta(minutes=1)
            if verifycode.add_time < one_minute_ago:
                raise serializers.ValidationError('验证码过期')
            else:
                # 判断验证码是否正确
                if verifycode.code != code:
                    raise serializers.ValidationError('验证码错误')
        else:
            raise serializers.ValidationError('请重新发送验证码')

    def validate(self, attrs):
        del attrs['code']
        return attrs

    class Meta:
        model = User
        fields = ['username', 'phone', 'email', 'code', 'password']


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'phone', 'gender']
